<template>
    <div v-if="easyFlowVisible">
        <!-- <el-row> -->
            <!--顶部工具菜单-->
            <!-- <el-col :span="24">
                <div class="ef-tooltar"> -->
                    <!-- <el-link type="primary" :underline="false">{{data.name}}</el-link> -->
                    <!-- <el-divider direction="vertical"></el-divider>
                    <el-button type="text" icon="el-icon-delete" size="large" @click="deleteElement" :disabled="!this.activeElement.type"></el-button>
                    <el-divider direction="vertical"></el-divider>
                    <el-button type="text" icon="el-icon-download" size="large" @click="downloadData"></el-button> -->
                <!-- </div>
            </el-col>
        </el-row> -->
        <div class="nodeMain">


         <div class="nodeLeft">

            <!-- 流程示意图部分 -->
            <div class="flow-wrap">
                <img src="/static/images/flow.jpg" class="flow-image" alt="">
            </div>

            <!-- 旅程定制部分 -->
            <div class="flow-sketch">
                <span class="dot"></span>
                <span class="title">旅程定制</span>
            </div>

            <!-- 中间画图部分 -->
            <div id="efContainer" ref="efContainer" class="container" v-flowDrag @click="closeList()"  style="min-heihgt: 500px;">
                <template v-for="node in data.nodeList">
                    <flow-node
                        :id="node.nodeId"
                        :key="node.nodeId"
                        :node="node"
                        :activeElement="activeElement"
                        @changeNodeSite="changeNodeSite"
                        @clickNode="clickNode(node)"
                        @deleteNodes="deleteElement(node)"
                        @setting="setting(node)"
                        @dblclick="setting(node)"
                        @contextmenu.prevent.native="rightClick(node)"
                    ></flow-node>

                </template>
                <!-- 给画布一个默认的宽度和高度 -->
                <div style="position:absolute;top: 500px;left: 500px;">&nbsp;</div>

            </div>

            <!-- 保存按钮 -->
            <div class="btns">
                <flow-node-form v-show="false" ref="nodeForm" @setLineLabel="setLineLabel"></flow-node-form>
                <div>
                    <el-button type="primary" block size="small" @click="cancelFun">取消</el-button>
                    <el-button type="primary" size="small" @click="submit(true)">确定并提交</el-button>
                    <el-button type="primary" size="small" @click="submit(false)">保存草稿</el-button>
                </div>
            </div>
        </div>
            <!-- 右侧拖拽标签部分 -->
            <div class="nodeRight">
                <node-menu @addNode="addNode" ref="nodeMenu"></node-menu>
            </div>

        </div>
        <!-- 流程数据详情 -->
        <flow-info v-if="flowInfoVisible" ref="flowInfo" :data="data"></flow-info>


        <!-- 标签选择标签弹窗内容 -->
        <el-dialog
            :visible.sync="showSetting"
            v-if="showSetting"
            :close-on-click-modal="false"
            :before-close="handleClose"
            :class="{longDialog:isLong,middleDialog:isMiddle,shortDialog:isShort,shortDialogPadding:isShort}"           
             >
            <userGroupSelection v-if="templateCode == 'user_group_selection_node'" :node-info="currentNode" :journeyId="journeyId" @saveLabelData="saveLabelData" @handleClose="handleClose"></userGroupSelection>
            <labelSelection v-if="templateCode == 'label_selection_node'" :node-info="currentNode" :journeyId="journeyId" @saveLabelData="saveLabelData" @handleClose="handleClose"></labelSelection>
            <eventSelection v-if="templateCode == 'event_selection_node'" :node-info="currentNode" :journeyId="journeyId" @saveLabelData="saveLabelData" @handleClose="handleClose"></eventSelection>
            <eventJudge v-if="templateCode == 'event_judge_node'" :node-info="currentNode" :journeyId="journeyId" @saveLabelData="saveLabelData" @handleClose="handleClose"></eventJudge>
            <sendCoupon v-if="templateCode == 'send_coupon_node'" :nodeInfo="currentNode" :journeyId="journeyId" @saveLabelData="saveLabelData" @changeCouponDlg="handleClose"/>
            <sendRedEnvelope v-if="templateCode == 'send_red_envelope_node'" :node-info="currentNode" :journeyId="journeyId" @saveLabelData="saveLabelData" @changeCouponDlg="handleClose"/>
            <sendMarket v-if="templateCode == 'send_market_node'" :node-info="currentNode" :journeyId="journeyId" @saveLabelData="saveLabelData" @changeCouponDlg="handleClose"/>
            <sms v-if="templateCode == 'send_sms_node'" :node-info="currentNode" :journeyId="journeyId" @saveLabelData="saveLabelData" @handleClose="handleClose"/>
            <mail v-if="templateCode == 'send_mail_node'" :node-info="currentNode" :journeyId="journeyId" @saveLabelData="saveLabelData" @handleClose="handleClose"/>
            <goods v-if="templateCode == 'send_goods_node'" :node-info="currentNode" :journeyId="journeyId" @saveLabelData="saveLabelData" @handleClose="handleClose"/>
            <timeTrigger v-if="templateCode == 'timed_trigger_node'" :node-info="currentNode" :journeyId="journeyId" @saveLabelData="saveLabelData" @handleClose="handleClose"/>
            <wait v-if="templateCode == 'wait_node'" :node-info="currentNode" :journeyId="journeyId" @saveLabelData="saveLabelData" @handleClose="handleClose"/>
<!--            <waitInfo v-if="templateCode == 'wait_node'" :node-info="currentNode" :journeyId="journeyId" @saveLabelData="saveLabelData" @handleClose="handleClose"/>-->
<!--            <timeTriggerInfo v-if="templateCode == 'timed_trigger_node'" :node-info="currentNode" :journeyId="journeyId" @saveLabelData="saveLabelData" @handleClose="handleClose"/>-->
<!--            <labelSelectionInfo v-if="templateCode == 'label_selection_node'" :node-info="currentNode" :journeyId="journeyId" @saveLabelData="saveLabelData" @handleClose="handleClose"></labelSelectionInfo>-->
        </el-dialog>

    </div>

</template>

<script>
    import draggable from 'vuedraggable'
    import './jsplumb'
    import { easyFlowMixin } from '@/components/AutoMarket/setPath/mixins'
    import flowNode from '@/components/AutoMarket/setPath/node'
    import nodeMenu from '@/components/AutoMarket/setPath/node_menu'
    import FlowInfo from '@/components/AutoMarket/setPath/info'
    import FlowNodeForm from './node_form'
    import lodash from 'lodash'
    import { getDataC } from './data_C'
    import labelSelection from '@/components/AutoMarket/labelSelection'
    import userGroupSelection from '@/components/AutoMarket/userGroupSelection'
    import eventSelection from '@/components/AutoMarket/eventSelection'
    import eventJudge from '@/components/AutoMarket/eventJudge'
    import sendCoupon from '@/components/AutoMarket/sendCoupon'
    import sendMarket from '@/components/AutoMarket/sendMarket'
    import sendRedEnvelope from '@/components/AutoMarket/sendRedEnvelope'
    import mail from '@/components/AutoMarket/sendMail'
    import sms from '@/components/AutoMarket/sendSms'
    import goods from "@/components/AutoMarket/sendGoods";
    import wait from "@/components/AutoMarket/wait";
    import timeTrigger from "@/components/AutoMarket/timeTrigger";
    import waitInfo from "@/components/AutoMarket/tripView/waitInfo";
    import timeTriggerInfo from "@/components/AutoMarket/tripView/timeTriggerInfo";
    import labelSelectionInfo from '@/components/AutoMarket/tripView/labelSelectionInfo'

    export default {
        data() {
            return {
                jsPlumb: null,                   // jsPlumb 实例
                easyFlowVisible: true,           // 控制画布销毁
                flowInfoVisible: true,           // 控制流程数据显示与隐藏
                // 是否加载完毕标志位
                loadEasyFlowFinish: false,
                // 数据
                data: {},
                // 激活的元素、可能是节点、可能是连线
                activeElement: {
                    // 可选值 node 、line
                    type: undefined,
                    // 节点ID
                    nodeId: undefined,
                    // 连线ID
                    sourceId: undefined,
                    targetId: undefined
                },
                nextLabelList: [],                      // 下一级别能链接的标签数据
                currentNode: {},                        // 点击编辑时该标签的数据信息
                showSetting: false,                     // 是否显示编辑弹窗
                templateCode: '',                        // 选中节点模板code
                tripInfo: {},                           // 旅程信息
                startNumber: 1,                         // 开始标签添加次数
                isLong:false,                           //弹框宽度(大)
                isMiddle:false,                         //弹框宽度（中）
                isShort:false,                          //弹框宽度（小）

            }
        },
        computed: {
            mainTabs: {
                get() {
                    return this.$store.state.tab.mainTabs;
                },
                set(val) {
                    this.$store.commit("updateMainTabs", val);
                }
            },
            mainTabsActiveName: {
                get() {
                    return this.$store.state.tab.mainTabsActiveName;
                },
                set(val) {
                    this.$store.commit("updateMainTabsActiveName", val);
                }
            }
        },
        props: {
            // 旅程ID
            journeyId: {
                type: String,
                default: '',
            },
            // 是否从编辑页面跳转，如果是，请求借口进行数据赋值
            isEdit: {
                type: Boolean,
                default: false,
            },
            timeType: {
                type: String,
                default: '1',
            }
        },
        // 一些基础配置移动该文件中
        mixins: [easyFlowMixin],
        components: {
            draggable, flowNode, nodeMenu, FlowInfo, FlowNodeForm,labelSelection,eventSelection,eventJudge,
            sendCoupon , sendRedEnvelope , sendMarket, sms, mail ,goods, userGroupSelection,wait,timeTrigger,waitInfo,timeTriggerInfo,labelSelectionInfo
        },

        directives: {
            'flowDrag': {
                bind(el, binding, vnode, oldNode) {
                    if (!binding) {
                        return
                    }
                    el.onmousedown = (e) => {
                        //  鼠标按下，计算当前原始距离可视区的高度
                        let disX = e.clientX
                        let disY = e.clientY
                        el.style.cursor = 'move'

                        document.onmousemove = function (e) {
                            // 移动时禁止默认事件
                            e.preventDefault()
                            const left = e.clientX - disX
                            disX = e.clientX
                            el.scrollLeft += -left
                            const top = e.clientY - disY
                            disY = e.clientY
                            el.scrollTop += -top
                        }

                        document.onmouseup = function (e) {
                            el.style.cursor = 'auto'
                            document.onmousemove = null
                            document.onmouseup = null
                        }
                    }
                }
            }
        },

        mounted() {
            let that = this;
            that.jsPlumb = jsPlumb.getInstance()
            that.$nextTick(() => {

                // 查看当前页面是否为编辑页面，如果是掉接口查询数据进行回显
                if(that.isEdit) {
                    let params = {
                        tripId: that.journeyId,
                        actionType:2
                    }
                    that.utils.request.getTripDetailAndNodeList(params,function(res) {
                        if(res.data) {
                            that.tripInfo = res.data;
                            
                            // 旅程流程图赋值
                            let nodeList = that.tripInfo.tripBranchNodeDetailResponseList;
                            let originalLists = that.tripInfo.lineList;

                            // 封装数据进行匹配插件
                            nodeList.forEach((item) => {
                                item.id = item.nodeId;
                                item.showList = false;
                                item.templateCode = item.nodeTemplateCode;

                                // 检测是否存在开始标签，如果存在不匀速拖拽
                                if(item.nodeTemplateCode == 'start_node') {
                                    that.startNumber = 2;
                                }

                                // 如果标签是事件判断，判断branchConditionList是否等于null，如果等于赋值为空数组，在连线的时候回判断
                                if(item.nodeTemplateCode == 'event_judge_node') {
                                    if(item.branchConditionList ==null) {
                                        item.branchConditionList = [];
                                    }
                                }
                            })
                            that.data.nodeList = nodeList;
                            that.data.lineList = originalLists;
                            // 初始化流程图
                            that.dataReload(that.data);
                        }
                    })
                }else {
                    let data = {
                        nodeList: [],
                        lineList: [],
                    }
                    this.dataReload(data)
                }
                
            });

            // 给数组添加contains方法
            Array.prototype.contains = function(obj) {
                var i = this.length;
                while (i--) {
                    if (this[i] === obj) {
                        return true;
                    }
                }
                return false;
            };

            // 添加数组对象定义一个函数，用于查找指定的元素在数组中的位置
            Array.prototype.indexOf = function(val) {
                for (var i = 0; i < this.length; i++) {
                    if (this[i] == val) return i;
                    }
                return -1;
            };

            // 使用js数组自己固有的函数去删除这个元素
            Array.prototype.remove = function(val) {
                var index = this.indexOf(val);
                if (index > -1) {
                    this.splice(index, 1);
                }
            };
            
            
        },

        methods: {

            // 保存创建数据，当营销时间是无固定时间时，弹框提示-确定后和后台进行交互，   固定时间段直接交互，成功后toast提示后跳转到下个页面

            submit(type) {
                let that = this;
                // 保存草稿
                if(!type) {
                    let data = that.data;
                    let params = {
                        tripId: Number(that.journeyId),
                        saveType: type,
                        nodeList: data.nodeList,
                        lineList: JSON.stringify(data.lineList)
                    };
                    that.utils.request.saveTripData(params,function(res) {
                        if(res.data) {
                            that.$message.success('提交成功！')
                            setTimeout(() => {
                                that.$router.push({
                                    path: `/pages/AutoMarket/UserJourneyManagement/SetDown?type=${type}`
                                })
                            },1000)
                        }
                    })
                } else {
                    // 保存并提交
                    if(that.timeType == '1') {
                        let data = that.data;
                        let params = {
                            tripId: Number(that.journeyId),
                            saveType: type,
                            nodeList: data.nodeList,
                            lineList: JSON.stringify(data.lineList)
                        };
                        that.utils.request.saveTripData(params,function(res) {
                            if(res.data) {
                                that.$message.success('提交成功！')
                                setTimeout(() => {
                                    that.$router.push({
                                        path: `/pages/AutoMarket/UserJourneyManagement/SetDown?type=${type}`
                                    })
                                },1000)
                            }
                        })
                    }else {
                        that.$confirm('<p>您确定保存并提交该旅程？</p><p style="color:red">本旅程无时间限制，提交后将立即开始</p>', '提示', {
                            dangerouslyUseHTMLString: true,
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning',
                            closeOnClickModal: false
                        }).then(() => {
                            let data = that.data;
                            let params = {
                                tripId: Number(that.journeyId),
                                saveType: type,
                                nodeList: data.nodeList,
                                lineList: JSON.stringify(data.lineList)
                            };
                            that.utils.request.saveTripData(params,function(res) {
                                if(res.data) {
                                    that.$message.success('提交成功！')
                                    setTimeout(() => {
                                        that.$router.push({
                                            path: `/pages/AutoMarket/UserJourneyManagement/SetDown?type=${type}`
                                        })
                                    },1000)
                                }
                            })
                        }).catch(() => {})
                    }
                }




            },

            // 点击设置图标触发方法
            setting(node) {
                this.currentNode = node;
                this.templateCode = node.templateCode;
                if(this.templateCode == 'wait_node' || this.templateCode == 'timed_trigger_node'){
                    this.isShort = true
                    this.isMiddle = false
                    this.isLong = false
                    this.showSetting = true;
                }else if(this.templateCode == 'event_selection_node' || this.templateCode == 'user_group_selection_node'||this.templateCode == 'event_judge_node'||this.templateCode == 'send_sms_node'||this.templateCode == 'send_mail_node'){
                    this.isShort = false
                    this.isMiddle = true
                    this.isLong = false
                    this.showSetting = true;
                }else if(this.templateCode == 'label_selection_node'||this.templateCode == 'send_coupon_node'||this.templateCode == 'send_red_envelope_node'||this.templateCode == 'send_market_node'||this.templateCode == 'send_goods_node'){
                    this.isShort = false
                    this.isMiddle = false
                    this.isLong = true

                    this.showSetting = true;
                }
            },

            // 关闭设置的弹窗
            handleClose() {
                this.showSetting = false;
            },

            // 保存标签选择弹框设置的返回数据，进行数据的回显,判断当前点击的组件，对比标签列表中的数据，添加一个描述的属性
            saveLabelData(data) {
               this.showSetting = false;
               let currentNode = this.currentNode;
               let nodeList= this.data.nodeList;
                nodeList.forEach((item) => {
                    if(currentNode.nodeId == item.nodeId) {
                        this.$set(item,'nodeName',data.nodeName);
                    }
                })
            },

            // 返回唯一标识
            getUUID() {
                return Math.random().toString(36).substr(3, 10)
            },

            jsPlumbInit() {
                this.jsPlumb.ready(() => {
                    // 导入默认配置
                    this.jsPlumb.importDefaults(this.jsplumbSetting)
                    // 会使整个jsPlumb立即重绘。
                    this.jsPlumb.setSuspendDrawing(false, true);
                    // 初始化节点
                    this.loadEasyFlow()
                    // 单点击了连接线, https://www.cnblogs.com/ysx215/p/7615677.html
                    this.jsPlumb.bind('click', (conn, originalEvent) => {
                        this.activeElement.type = 'line'
                        this.activeElement.sourceId = conn.sourceId
                        this.activeElement.targetId = conn.targetId
                        this.$refs.nodeForm.lineInit({
                            from: conn.sourceId,
                            to: conn.targetId,
                            label: conn.getLabel()
                        })
                    })

                    // 连线
                    this.jsPlumb.bind("connection", (evt) => {
                        let from = evt.source.id
                        let to = evt.target.id
                        if (this.loadEasyFlowFinish) {
                            this.data.lineList.push({from: from, to: to})
                        }
                    })

                    // 删除连线回调
                    this.jsPlumb.bind("connectionDetached", (evt) => {
                        this.deleteLine(evt.sourceId, evt.targetId)
                    })

                    // 改变线的连接节点
                    this.jsPlumb.bind("connectionMoved", (evt) => {
                        this.changeLine(evt.originalSourceId, evt.originalTargetId)
                    })

                    // 连线右击
                    this.jsPlumb.bind("contextmenu", (evt) => {
                    })

                    // 连线前判断是否能链接
                    this.jsPlumb.bind("beforeDrop", (evt) => {
                        // 根据开始标签ID和结束标签ID获取到两个标签的数据
                        // 获取到开始节点的可连接下级，和结束节点的模板code值，判断结束标签的code是否存在于开始节点的可连接下级，如果存在才可以连线，不存在就不可以连线

                        let from = evt.sourceId;            // 开始标签ID
                        let to = evt.targetId;              // 结束标签ID
                        let list = this.data.nodeList;      // 所有标签列表
                        let startNode = {};                 // 开始标签数据，如果该节点有
                        let endNode = {};                   // 结束标签数据，验证该节点是否已经存在父节点



                        // 节点不支持链接自己
                        if (from === to) {
                            this.$message.error('节点不支持连接自己')
                            return false
                        }

                        // 不允许重复创建
                        if (this.hasLine(from, to)) {
                            this.$message.error('该节点只能链接一次，请从右侧拖拽一个新节点')
                            return false
                        }

                        // 不支持两个标签之间回链
                        if (this.hashOppositeLine(from, to)) {
                            this.$message.error('不支持两个节点之间连线回环');
                            return false
                        }


                        // 不支持不允许的标签连线
                        list.forEach((item) => {
                            if(item.nodeId == from ) {
                                startNode = item;
                            }
                            if(item.nodeId == to ) {
                                endNode = item;
                            }
                        })

                        // 不支持一个节点同时出现两个父节点
                        if(endNode.parentId &&　endNode.parentId　!= '') {
                            return;
                        }


                        // 判断结束标签的code是否存在于开始节点的可连接下级，如果存在才可以连线，不存在就不可以连线
                        if(!startNode.nextTemplateCodes.includes(endNode.templateCode)) {
                            this.$message.error('该节点间不能链接');
                            return;
                        }

                        // 开始标签允许链接无数子标签， 事件判断可以链接两个，其他的标签只能链接一个
                        if(startNode.templateCode != 'start_node' && startNode.templateCode != 'event_judge_node' && startNode.chirldrenId.length >= 1) {
                            return;
                        }

                        if(startNode.templateCode == 'event_judge_node' && startNode.chirldrenId.length >= 2) {
                            return;
                        }

                        // 掉接口将开始标签ID和结束标签ID传给后台
                        let params = {
                            tripId: Number(this.journeyId),
                            id: Number(endNode.nodeId),
                            prevBranchNodeId: Number(startNode.nodeId),
                            checkUpdateChild: true,
                        }

                        // 当标签为事件判断时候，添加是否标识
                        // 先判断事件判断branchConditionList.length长度， 等于0的时候，branchCondition值为1（默认第一个条件为是）
                        // length长度 == 1的时候，判断自定义的属性，如果是1  那么branchCondition的值取第一个的反向值， 保持一是一否
                        // 掉接口成功后前端添加自定义属性，将该次提交的值保存，在删除标签后将该值进行删除

                        if(startNode.templateCode == 'event_judge_node') {
                            let branchConditionList = startNode.branchConditionList;
                            if(!branchConditionList) {
                                return;
                            }
                            if(branchConditionList.length == 0) {
                                params.branchCondition = 1;
                            }else {
                                params.branchCondition = branchConditionList[0].branchCondition == 0 ? 1 : 0;
                            }
                        }
                        let that = this;
                        that.utils.request.updateBranchNode(params,function(res) {
                            if(res.data) {
                                // 编辑成功后在结束标签里面添加自定义父ID，防止其他标签再链接这个节点,
                                // 在开始标签里面添加自定义子ID列表， 删除父标签的时候将该标签的所有子标签的父ID置空，防解决重新链接不上的问题
                                endNode.parentId = startNode.nodeId;
                                startNode.chirldrenId.push(endNode.nodeId);
                                that.$message.success('连接成功');

                                // 事假判断标签连线后添加连线文字
                                if(startNode.templateCode == 'event_judge_node') {
                                    // 链接成功后 添加自定义是否标签
                                    startNode.branchConditionList.push({
                                        branchCondition: params.branchCondition +'',
                                    });
                                    endNode.branchCondition = params.branchCondition+'';
                                    let judge = '';
                                    judge = params.branchCondition == 1 ? '是' : '否';
                                    that.setLineLabel(startNode.nodeId,endNode.nodeId,judge);
                                }

                            }
                        });
                        return true;
                    })

                    // beforeDetach
                    // this.jsPlumb.bind("beforeDetach", (evt) => {
                    // })
                    this.jsPlumb.setContainer(this.$refs.efContainer)
                })
            },

            // 加载流程图
            loadEasyFlow() {
                // 初始化节点
                for (var i = 0; i < this.data.nodeList.length; i++) {
                    let node = this.data.nodeList[i]
                    // 设置源点，可以拖出线连接其他节点
                    this.jsPlumb.makeSource(node.id, this.jsplumbSourceOptions)
                    // // 设置目标点，其他源点拖出的线可以连接该节点
                    this.jsPlumb.makeTarget(node.id, this.jsplumbTargetOptions)
                    this.jsPlumb.draggable(node.id, 'item_left', {containment: 'parent'},'item_top', {containment: 'parent'})
                }
                // 初始化连线
                for (var i = 0; i < this.data.lineList.length; i++) {
                    let line = this.data.lineList[i];
                    var connParam = {
                        source: line.from,
                        target: line.to,
                        label: line.label ? line.label : '',
                        connector: line.connector ? line.connector : '',
                        anchors: line.anchors ? line.anchors : undefined,
                        paintStyle: line.paintStyle ? line.paintStyle : undefined,
                    }
                    this.jsPlumb.connect(connParam, this.jsplumbConnectOptions);
                }
                this.$nextTick(function () {
                    this.loadEasyFlowFinish = true
                })
            },

            // 连线之间添加文字
            setLineLabel(from, to, label) {
                var conn = this.jsPlumb.getConnections({
                    source: from,
                    target: to
                })[0]
                if (!label || label === '') {
                    conn.removeClass('flowLabel')
                    conn.addClass('emptyFlowLabel')
                } else {
                    conn.addClass('flowLabel')
                }
                conn.setLabel({
                    label: label,
                })
                this.data.lineList.forEach(function (line) {
                    if (line.from == from && line.to == to) {
                        line.label = label
                    }
                })

            },

            // 删除激活的元素
            deleteElement() {
                if (this.activeElement.type === 'node') {
                    if(this.activeElement.nodeId.templateCode == 'start_node') {
                        return this.$message.error("开始标签不允许删除")
                    }
                    this.deleteNode(this.activeElement.nodeId)
                } else if (this.activeElement.type === 'line') {
                    this.$confirm('确定删除所点击的线吗?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        var conn = this.jsPlumb.getConnections({
                            source: this.activeElement.sourceId,
                            target: this.activeElement.targetId
                        })[0]
                        this.jsPlumb.deleteConnection(conn)
                    }).catch(() => {
                    })
                }
            },

            // 删除线
            deleteLine(from, to) {
                this.data.lineList = this.data.lineList.filter(function (line) {
                    if (line.from == from && line.to == to) {
                        return false
                    }
                    return true
                })
            },

            // 改变连线
            changeLine(oldFrom, oldTo) {
                this.deleteLine(oldFrom, oldTo)
            },

            // 改变节点的位置
            changeNodeSite(data) {
                for (var i = 0; i < this.data.nodeList.length; i++) {
                    let node = this.data.nodeList[i]
                    if (node.id === data.nodeId) {
                        node.left = data.left
                        node.top = data.top
                    }
                }
            },

            /**
             * 拖拽结束后添加新的节点
             * @param evt
             * @param nodeMenu 被添加的节点对象
             * @param mousePosition 鼠标拖拽结束的坐标
             */
            addNode(evt, nodeMenu, mousePosition) {
                let this_ = this;
                var screenX = evt.originalEvent.clientX, screenY = evt.originalEvent.clientY
                let efContainer = this_.$refs.efContainer
                var containerRect = efContainer.getBoundingClientRect();

                var left = screenX, top = screenY
                // 计算是否拖入到容器中
                if (left < containerRect.x || left > containerRect.width + containerRect.x || top < containerRect.y || containerRect.y > containerRect.y + containerRect.height) {
                    this_.$message.error("请把节点拖入到画布中")
                    return
                }
                left = left - containerRect.x + efContainer.scrollLeft
                top = top - containerRect.y + efContainer.scrollTop

                // 居中
                left -= 85
                top -= 16


                // 调后台的新增方法，将返回的标签ID复制给组件，在设置的时候使员,  只有时间选择标签才传branchCondition字段，值为1，代表该字段有分支条件，后台使用
                let params = {
                    nodeTemplateCode: nodeMenu.templateCode,
                    tripId: Number(this_.journeyId),
                    top: top,
                    left: left,
                };
                if(nodeMenu.templateCode == 'event_selection_node') {
                    params.branchCondition = 1;
                }


                // 拦截开始标签拖拽次数，
                let startNumber = this_.startNumber;
                if(startNumber >1 && nodeMenu.templateCode == 'start_node') {
                    return this_.$message.error('开始节点只允许拖拽一次')
                }

                let labelId = '';   // 当前标签后台返回的ID，编辑的时候要使用
                this_.utils.request.updateBranchNode(params,function(res) {
                    if(res.data) {
                        if(params.nodeTemplateCode == 'start_node') {
                            this_.startNumber += 1;
                        }

                        labelId = res.data;
                        // 注释原有的获取nodeId方法
                        // var nodeId = this_.getUUID()
                        var id = nodeMenu.id;
                        var nodeId = labelId;
                        var templateCode = nodeMenu.templateCode;
                        var nextTemplateCodes = nodeMenu.nextTemplateCodes;
                        var templateType = nodeMenu.templateType;
                        var nodeName = nodeMenu.templateName;
                        var index = 1;
                        var chirldrenId = [];
                        var branchConditionList = [];        // 事件判断标签专门添加的属性，记录该标签向下链接字标签是或者否

                        // 同一个标签拖拽多次的时候将当前标签的原始ID 进行变更  否则添加不进去
                        // 开始标签只能添加一次
                        // while (index < 20) {
                        //     var repeat = false;
                        //     for (let i = 0; i < this_.data.nodeList.length; i++) {
                        //         let node = this_.data.nodeList[i];
                        //         if (node.name === nodeName ) {
                        //             id += 1
                        //             repeat = true;
                        //             break;
                        //         }
                        //     }
                        //     if (repeat) {
                        //         index++
                        //         continue
                        //     }
                        //     break
                        // }
                        var node = {
                            id: labelId,
                            name: nodeName,
                            left: left + 'px',
                            top: top + 'px',
                            ico: nodeMenu.ico,
                            showList: false,
                            nodeId: labelId,
                            templateCode: templateCode,
                            nextTemplateCodes: nextTemplateCodes,
                            templateType: templateType,
                            chirldrenId: chirldrenId,
                            eventType: 0,
                        }

                        // 如果是事件判断  添加自定义属性，记录添加的分支为是或者否
                        if(node.templateCode == 'event_judge_node') {
                            node.branchConditionList = branchConditionList;
                        }

                        /**
                         * 这里可以进行业务判断、是否能够添加该节点
                         */
                        this_.data.nodeList.push(node);
                        node = {};
                        this_.$nextTick(function () {
                            this_.jsPlumb.makeSource(nodeId,nextTemplateCodes,this_.jsplumbSourceOptions)
                            this_.jsPlumb.makeTarget(nodeId,nextTemplateCodes,this_.jsplumbTargetOptions)
                            this_.jsPlumb.draggable(nodeId,nextTemplateCodes,'item_left', {containment: 'parent'},'item_top', {containment: 'parent'})
                        })
                    }
                });


            },

            /**
             * 删除节点
             * @param nodeId 被删除节点的ID
             */
            deleteNode(node) {
                let this_ = this;
                this_.$confirm('确定要删除节点' + node.name + '?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    closeOnClickModal: false
                }).then(() => {
                    // 调后台接口进行删除，删除成功后将前端的数据进行处理
                    let params = {
                        branchNodeId: node.nodeId,
                        nodeTemplateCode: node.templateCode,
                    };
                    this_.utils.request.deleteLabel(params,function(res) {
                        if(res.data) {
                            // 追加到中间面板中
                            this_.data.nodeList = this_.data.nodeList.filter(function (value) {
                                if (node.nodeId === value.nodeId) {
                                    // 伪删除，将节点隐藏，否则会导致位置错位
                                    node.show = false;

                                    // 将该标签下面的所有已连接的子标签的parentId全部置空，保证可以重新链接
                                    let chirldreLists = node.chirldrenId;
                                    let nodeList = this_.data.nodeList;
                                    let parentId = node.parentId;


                                    // 删除该标签已连接子元素的parentId
                                    if(chirldreLists.length > 0) {
                                        chirldreLists.forEach((item) => {
                                            nodeList.forEach((itm) => {
                                                if(item == itm.nodeId) {
                                                    delete itm.parentId;
                                                }
                                            })
                                        });
                                    }


                                    // 删除改标签父元素的已连接子元素的数量（删除自己）
                                    this_.data.nodeList.forEach(f=>{
                                        if(f.nodeId == node.parentId){
                                            let chirlds = f.chirldrenId.filter(e=>{
                                                return e != node.nodeId;
                                            })
                                            f.chirldrenId=chirlds;
                                            // 删除父标签中branchCondition条件相等的数据
                                            if(f.templateCode == 'event_judge_node') {
                                                var list = f.branchConditionList;
                                                for( var i = 0 ; i < list.length; i++ ) {
                                                    if(node.branchCondition == list[i].branchCondition) {
                                                        list.splice(i,1)
                                                    }
                                                }
                                            }
                                        }
                                    });

                                    // 如果该标签是事件判断,删除所有子标签的branchCondition属性
                                    if(node.templateCode == 'event_judge_node') {
                                        let chirldrenId = node.chirldrenId;
                                        chirldrenId.forEach((item) => {
                                            nodeList.forEach((itm) => {
                                                if(item == itm.nodeId) {
                                                    delete itm.branchCondition;
                                                }
                                            })
                                        });
                                    }

                                    this_.$nextTick(function () {
                                        this_.jsPlumb.removeAllEndpoints(node.nodeId);
                                    })
                                    return false
                                }
                                return true
                            })
                            this_.$nextTick(function () {
                                this_.jsPlumb.removeAllEndpoints(node.nodeId);
                            })
                        }
                    });

                }).catch(() => {
                })
                return true
            },

            // 点击标签
            clickNode(nodeId) {
                this.activeElement.type = 'node'
                this.activeElement.nodeId = nodeId
                this.$refs.nodeForm.nodeInit(this.data, nodeId);
                // 点击删除按钮后将当前node元素传递给删除方法  执行删除动作
                this.deleteElement();
            },

            // 右键事件
            rightClick(item){

                // 先将所有标签的右侧的弹出框关闭，再将当前标签所在的弹出框打开
                this.data.nodeList.forEach((item) => {
                    item.showList = false;
                })
                this.nextLabelList = [];

                // 根据当前标签内的可连接标签数据，显示对应的文案
                if(item.nextTemplateCodes && item.nextTemplateCodes.length > 0) {
                    const list = item.nextTemplateCodes.split(',');
                    list.forEach((item) => {
                        let data = {};
                        if( item == 'label_selection_node' ) {
                            data.title = '标签选择';
                            this.nextLabelList.push(data);
                        }
                        if( item == 'user_group_selection_node' ) {
                            data.title = '用户组选择';
                            this.nextLabelList.push(data);
                        }
                        if( item == 'event_selection_node' ) {
                            data.title = '事件选择';
                            this.nextLabelList.push(data);
                        }
                        if( item == 'timed_trigger_node' ) {
                            data.title = '定时触发';
                            this.nextLabelList.push(data);
                        }
                        if( item == 'wait_node' ) {
                            data.title = '等待';
                            this.nextLabelList.push(data);
                        }
                        if( item == 'event_judge_node' ) {
                            data.title = '事件判断';
                            this.nextLabelList.push(data);
                        }
                        if( item == 'send_coupon_node' ) {
                            data.title = '发放优惠券';
                            this.nextLabelList.push(data);
                        }
                        if( item == 'send_red_envelope_node' ) {
                            data.title = '发放红包';
                            this.nextLabelList.push(data);
                        }
                        if( item == 'send_market_node' ) {
                            data.title = '推送促销活动';
                            this.nextLabelList.push(data);
                        }
                        if( item == 'send_goods_node' ) {
                            data.title = '推送商品信息';
                            this.nextLabelList.push(data);
                        }
                        if( item == 'send_graphic_node' ) {
                            data.title = '推送图文';
                            this.nextLabelList.push(data);
                        }
                        if( item == 'send_sms_node' ) {
                            data.title = '发短信';
                            this.nextLabelList.push(data);
                        }
                        if( item == 'send_wechat_node' ) {
                            data.title = '发微信消息';
                            this.nextLabelList.push(data);
                        }
                        if( item == 'send_mail_node' ) {
                            data.title = '发邮件';
                            this.nextLabelList.push(data);
                        }
                        if( item == 'send_apppush_node' ) {
                            data.title = '发Apppush消息';
                            this.nextLabelList.push(data);
                        }
                        if( item == 'end_node' ) {
                            data.title = '结束';
                            this.nextLabelList.push(data);
                        }
                    });
                    item.nextLabelList = this.nextLabelList;
                    item.showList = true;
                }

            },

            // 点击页面中的任意的位置隐藏标签的弹框信息（可连接的标签列表）
            closeList() {
                if(this.data.nodeList && this.data.nodeList.length > 0) {
                    this.data.nodeList.forEach((item) => {
                        item.showList = false;
                    })
                }
            },

            // 是否具有该线
            hasLine(from, to) {
                for (var i = 0; i < this.data.lineList.length; i++) {
                    var line = this.data.lineList[i]
                    if (line.from === from && line.to === to) {
                        return true
                    }
                }
                return false
            },

            // 是否含有相反的线
            hashOppositeLine(from, to) {
                return this.hasLine(to, from)
            },

            // 加载流程图
            dataReload(data) {
                this.easyFlowVisible = false
                // this.data.nodeList = []
                // this.data.lineList = []
                this.$nextTick(() => {
                    data = lodash.cloneDeep(data)
                    this.easyFlowVisible = true
                    this.data = data
                    this.$nextTick(() => {
                        this.jsPlumb = jsPlumb.getInstance()
                        this.$nextTick(() => {
                            this.jsPlumbInit()
                        })
                    })
                })
            },

            // 下载数据
            downloadData() {
                var conn = this.jsPlumb.getConnections({
                    source: 'nodeA',
                    target: 'nodeB'
                })[0]
                this.$confirm('确定要下载该流程数据吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    closeOnClickModal: false
                }).then(() => {
                    var datastr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(this.data, null, '\t'));
                    var downloadAnchorNode = document.createElement('a')
                    downloadAnchorNode.setAttribute("href", datastr);
                    downloadAnchorNode.setAttribute("download", 'data.json')
                    downloadAnchorNode.click();
                    downloadAnchorNode.remove();
                    this.$message.success("正在下载中,请稍后...")
                }).catch(() => {
                })
            },

            // tabs, 删除tab
            removeTabHandle(tabName) {
                this.mainTabs = this.mainTabs.filter(item => item.name !== tabName);
                if (this.mainTabs.length >= 1) {
                    // 当前选中tab被删除
                    if (tabName === this.mainTabsActiveName) {
                        let tab = this.mainTabs[this.mainTabs.length - 1];
                        this.$router.push(
                            { path: tab.path,params: tab.params, query: tab.query},
                            () => {
                            this.mainTabsActiveName = this.$route.name;
                        }
                    );
                    }
                } else {
                    this.$router.push("/");
                }
            },
            cancelFun(){
                this.removeTabHandle("创建用户旅程二")
            }
        }
    }
</script>
<style scoped lang="scss">

/deep/ .el-dialog{
    padding-bottom: 80px !important;
    .el-dialog__header{
        padding: 50px 30px 0 !important;
    }
    .el-dialog__body{
        padding: 0 60px !important;
    }
    
}
.nodeMain{
    display: flex;
    justify-content: space-between;
}
.nodeLeft{
    width: calc(100% - 336px);
    border-top: 0 none;
    border: 1px solid #e7e7e7;
    .container{
        min-height: 880px;
        overflow: auto !important;
        /deep/ .ef-node-container{
            min-width: 190px;
            min-height: 50px;
            border:1px solid #222E49;
            background: #F6F9FF;
        }
    }
}
.nodeRight{
    width: 316px;
    border: 1px solid #e7e7e7;
}
.nodeLeft,.nodeRight{
    background: #fff;
}
.longDialog{
    /deep/ .el-dialog{
        width: 1254px !important;
    }
}
.middleDialog{
    /deep/ .el-dialog{
        width: 922px !important;
    }
}
.shortDialog{
    /deep/ .el-dialog{
        width: 610px !important;
    }
}
.shortDialogPadding{
    /deep/ .el-dialog{
        .el-dialog__body{
            padding: 0 90px !important;
        }
    }
}
.btns {
    margin-bottom: 30px;
    margin-top: 30px;
    border-top: 1px solid #e7e7e7;
    padding-top: 30px;
}

/* 流程示意图部分 */ 
.flow-wrap {
    display: block;
    width: 100%;
    height: 84px;
    .flow-image {
        display: block;
        width: 100%;
        height: 84px;
    }
}
/* 流程示意图部分样式 */
.flow-sketch {
    text-align: left;
    height: 40px;
    line-height: 40px;
    border: 1px solid #fff;
    margin-left: -1px;
    margin-right: -1px;
  .dot {
    display: inline-block;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background-color: #409EFF;
  }
  .title {
    display: inline-block;
    color: #333;
    font-size: 14px;
    margin-left: 5px;
  }
} 
</style>
